<template>
  <div class="home-container">
    <!-- 顶部导航栏 -->
    <el-header class="header">
      <div class="header-left">
        <div class="logo">
          <img src="/logo.png" alt="家政服务平台" />
          <span>家政服务平台</span>
        </div>
        <el-icon><Menu /></el-icon>
        <el-icon @click="refreshData"><Refresh /></el-icon>
        <span class="nav-text">首页</span>
      </div>
      <div class="header-right">
        <el-button class="client-btn">
          <el-icon><Monitor /></el-icon>
          客户端
        </el-button>
        <el-badge is-dot>
          <el-icon><Bell /></el-icon>
        </el-badge>
        <el-icon><Setting /></el-icon>
        <el-dropdown @command="handleCommand">
          <div class="user-info">
            <el-avatar :size="32">{{ userInitials }}</el-avatar>
            <span>{{ username }}</span>
            <el-icon><CaretBottom /></el-icon>
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="profile">个人信息</el-dropdown-item>
              <el-dropdown-item command="settings">账号设置</el-dropdown-item>
              <el-dropdown-item divided command="logout">
                <span style="color: #f56c6c;">注销</span>
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </el-header>

    <div class="main-container">
      <!-- 左侧菜单 -->
      <el-aside width="64px" class="sidebar">
        <router-link to="/admin" custom v-slot="{ navigate }">
          <div class="menu-item active">
            <el-icon><HomeFilled /></el-icon>
            <span>首页</span>
          </div>
        </router-link>
        <router-link to="/admin/service-management" custom v-slot="{ navigate }">
          <div class="menu-item" @click="navigate">
            <el-icon><Setting /></el-icon>
            <span>服务管理</span>
          </div>
        </router-link>
        <router-link to="/admin/user-management" custom v-slot="{ navigate }">
          <div class="menu-item" @click="navigate">
            <el-icon><User /></el-icon>
            <span>用户管理</span>
          </div>
        </router-link>
        <router-link to="/admin/application-management" custom v-slot="{ navigate }">
          <div class="menu-item" @click="navigate">
            <el-icon><Promotion /></el-icon>
            <span>审批系统</span>
          </div>
        </router-link>
        <router-link to="/admin/worker-management" custom v-slot="{ navigate }">
          <div class="menu-item" @click="navigate">
            <el-icon><User /></el-icon>
            <span>家政管理</span>
          </div>
        </router-link>
      </el-aside>

      <!-- 主要内容区域 -->
      <el-main class="main-content">
        <!-- 家政服务分类 -->
        <div class="recommended-apps">
          <h2>家政服务分类</h2>

          <div class="app-cards">
            <el-card
                v-for="(app, index) in recommendedApps"
                :key="index"
                class="app-card"
                shadow="hover"
                @click="showServiceStaff(app)">
              <div class="app-image" :style="{ backgroundColor: app.bgColor }">
                <img :src="app.image" :alt="app.title" />
              </div>
              <div class="app-title">{{ app.title }}</div>
              <div class="app-description">{{ app.description }}</div>
              <div class="app-meta">
                <div class="app-author">
                  <el-avatar :size="24">N</el-avatar>
                  <span>housekeeping</span>
                </div>
                <div class="app-stats">
                  <el-icon><Star /></el-icon> {{ app.stars }}
                  <el-icon><View /></el-icon> {{ app.views }}
                </div>
              </div>
            </el-card>
          </div>
        </div>

        <!-- 数据概况 -->
        <div class="statistics">
          <h2>数据概况</h2>
          <div class="stat-cards">
            <el-card v-for="(stat, index) in statistics" :key="index" class="stat-card">
              <div class="stat-value">{{ stat.value }}</div>
              <div class="stat-label">{{ stat.label }}</div>
            </el-card>
          </div>
        </div>
      </el-main>
    </div>

    <!-- 服务人员对话框 -->
    <el-dialog
        v-model="staffDialogVisible"
        :title="currentService ? `${currentService.title} - 服务人员列表` : '服务人员列表'"
        width="70%"
    >
      <div class="staff-search">
        <el-input v-model="staffSearchKeyword" placeholder="搜索服务人员" clearable>
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>

      <div class="staff-list" v-loading="loading">
        <el-empty v-if="filteredStaffList.length === 0" description="暂无服务人员" />
        <el-row :gutter="20" v-else>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" v-for="staff in filteredStaffList" :key="staff.id">
            <el-card class="staff-card" shadow="hover">
              <div class="staff-avatar">
                <el-avatar :size="80" :src="staff.avatar || ''">{{ staff.name ? staff.name.charAt(0) : 'U' }}</el-avatar>
              </div>
              <div class="staff-info">
                <h4>{{ staff.name }}</h4>
                <p class="staff-title">{{ staff.title || staff.service_type || '家政服务人员' }}</p>
                <div class="staff-rating">
                  <el-rate :value="staff.rating || 5" disabled text-color="#ff9900" />
                  <span>{{ staff.rating || 5 }}分</span>
                </div>
                <div class="staff-tags">
                  <el-tag size="small">{{ staff.service_type }}</el-tag>
                  <el-tag v-if="staff.experience" size="small">{{ staff.experience }}经验</el-tag>
                  <el-tag v-if="staff.worker_status" size="small" :type="staff.worker_status === '在职' ? 'success' : 'warning'">
                    {{ staff.worker_status }}
                  </el-tag>
                </div>
              </div>
              <div class="staff-actions">
                <el-button size="small" @click="viewStaffDetails(staff)">查看详情</el-button>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import {
  HomeFilled, Menu, Setting, Bell, Monitor, CaretBottom, Refresh,
  Promotion, User, Star, View, Search
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from "element-plus"
import {selectWorkerById, selectWorkerByServiceType} from "@/api/worker/worker.js";
import {getServiceList} from "@/api/service/service.js";

const router = useRouter()
const username = ref('admin')
const loading = ref(false)
const categoriesLoading = ref(false)
const userInitials = computed(() => {
  return username.value.charAt(0).toUpperCase()
})

// 服务类别数据 - 初始为空数组，将从API获取
const recommendedApps = ref([])

// 背景色数组，用于为类别分配颜色
const bgColors = ['#1989fa', '#ff4d4f', '#52c41a', '#fa541c', '#ff85c0', '#722ed1', '#13c2c2', '#faad14']

// 统计数据
const statistics = ref([
  { value: '342', label: '总访问量' },
  { value: '132', label: '平台用户数' },
  { value: '18', label: '家政人员数' },
  { value: '30', label: '历史成交订单' },
  { value: '1', label: '当前在线人数' }
])

// 从后端获取所有服务类别
const fetchCategories = async () => {
  try {
    categoriesLoading.value = true
    const response = await getServiceList();
    console.log('API响应:', response.data)
    if (response.data && response.data.code === 200) {
      // 将API返回的数据转换为我们需要的格式
      recommendedApps.value = (response.data.data || []).map((item, index) => {
        return {
          title: item.category, // 使用item.category而不是category.name
          description: item.discription || `专业${item.category}，提供优质服务`, // 使用item.discription而不是category.description
          image: item.image || `/app${(index % 5) + 1}.png`,
          bgColor: '#ffffff',
          stars: Math.floor(Math.random() * 5),
          views: Math.floor(Math.random() * 1000) + 100,
          id: item.id,
          categoryId: item.id
        }
      })

      if (recommendedApps.value.length === 0) {
        ElMessage.warning('暂无服务类别数据')
        // 如果API返回的数据为空，使用默认数据
        setDefaultCategories()
      }
    } else {
      ElMessage.error(response.data?.message || '获取服务类别失败')
      // 如果API获取失败，可以设置一些默认值
      setDefaultCategories()
    }
  } catch (error) {
    console.error('获取服务类别出错:', error)
    ElMessage.error('获取服务类别失败，使用默认数据')
    // 出错时使用默认数据
    setDefaultCategories()
  } finally {
    categoriesLoading.value = false
  }
}

// 设置默认类别数据（仅在API失败时使用）
const setDefaultCategories = () => {
  recommendedApps.value = [
    {
      title: '清洁服务',
      description: '专业家居清洁，让您的家焕然一新',
      image: '/app1.jpg',
      bgColor: '#ffffff',
      stars: 0,
      views: 1190,
      id: 1,
      categoryId: 1
    },
    {
      title: '照护服务',
      description: '专业的老人、儿童照护服务，让您安心无忧',
      image: '/app2.jpg',
      bgColor: '#ffffff',
      stars: 0,
      views: 485,
      id: 2,
      categoryId: 2
    },
    {
      title: '烹饪服务',
      description: '私人厨师上门，提供健康美味的家庭餐食',
      image: '/app3.jpg',
      bgColor: '#ffffff',
      stars: 2,
      views: 194,
      id: 3,
      categoryId: 3
    },
    {
      title: '维修服务',
      description: '家电、管道、电路等专业上门维修服务',
      image: '/app4.jpg',
      bgColor: '#ffffff',
      stars: 0,
      views: 62,
      id: 4,
      categoryId: 4
    },
    {
      title: '其他服务',
      description: '定制化家政服务，满足您的特殊需求',
      image: '/app5.jpg',
      bgColor: '#ffffff',
      stars: 0,
      views: 42,
      id: 5,
      categoryId: 5
    }
  ]
}

// 服务人员对话框
const staffDialogVisible = ref(false)
const currentService = ref(null)
const staffSearchKeyword = ref('')
const currentStaffList = ref([])

// 根据关键词过滤服务人员
const filteredStaffList = computed(() => {
  if (!staffSearchKeyword.value) {
    return currentStaffList.value
  }

  const keyword = staffSearchKeyword.value.toLowerCase()
  return currentStaffList.value.filter(staff =>
      staff.name?.toLowerCase().includes(keyword) ||
      staff.title?.toLowerCase().includes(keyword) ||
      staff.service_type?.toLowerCase().includes(keyword)
  )
})

// 从后端获取服务人员列表
const fetchWorkers = async (categoryId, categoryName) => {
  try {
    loading.value = true
    // 使用service_type或category字段查询，而不是id
    const response = await selectWorkerByServiceType(categoryName)

    console.log(response.data)

    if (response.data && response.data.code === 200) {
      // 从响应中提取工作人员列表
      return response.data.data || []
    } else {
      ElMessage.error(response.data.message || '获取服务人员列表失败')
      return []
    }
  } catch (error) {
    console.error('获取服务人员列表出错:', error)
    ElMessage.error('获取服务人员列表失败，请稍后重试')
    return []
  } finally {
    loading.value = false
  }
}

// 获取服务人员详情
const fetchWorkerDetails = async (id) => {
  try {
    loading.value = true
    const response = await selectWorkerById(id);

    if (response.data && response.data.code === 200) {
      return response.data.data
    } else {
      ElMessage.error(response.data.message || '获取服务人员详情失败')
      return null
    }
  } catch (error) {
    console.error('获取服务人员详情出错:', error)
    ElMessage.error('获取服务人员详情失败，请稍后重试')
    return null
  } finally {
    loading.value = false
  }
}

// 显示服务人员列表
const showServiceStaff = async (app) => {
  currentService.value = app
  staffSearchKeyword.value = ''
  staffDialogVisible.value = true

  // 获取对应服务类型的工作人员列表
  currentStaffList.value = await fetchWorkers(app.categoryId, app.title)

  // 增加点击量
  app.views++
}

// 查看服务人员详情
const viewStaffDetails = async (staff) => {
  try {
    const workerDetails = await fetchWorkerDetails(staff.id)
    if (workerDetails) {
      await ElMessageBox.alert(
          `<div>
          <p><strong>姓名:</strong> ${workerDetails.name}</p>
          <p><strong>性别:</strong> ${workerDetails.gender || '未设置'}</p>
          <p><strong>年龄:</strong> ${workerDetails.age || '未设置'}</p>
          <p><strong>联系电话:</strong> ${workerDetails.phone || '未设置'}</p>
          <p><strong>工作状态:</strong> ${workerDetails.status || '未设置'}</p>
          <p><strong>地址:</strong> ${workerDetails.address || '暂无描述'}</p>
        </div>`,
          '服务人员详情',
          {
            dangerouslyUseHTMLString: true,
            confirmButtonText: '关闭'
          }
      )
    }
  } catch (error) {
    console.error('显示服务人员详情出错:', error)
  }
}

// 刷新数据
const refreshData = async () => {
  await fetchCategories()

  // 如果当前正在显示某个分类的工作人员，则重新获取
  if (currentService.value && staffDialogVisible.value) {
    const updatedApp = recommendedApps.value.find(app => app.id === currentService.value.id)
    if (updatedApp) {
      await showServiceStaff(updatedApp)
    }
  }

  ElMessage.success('数据已刷新')
}

// 处理下拉菜单命令
const handleCommand = (command) => {
  if (command === 'logout') {
    logout()
  } else if (command === 'profile') {
    // 处理个人信息
    ElMessage.info('个人信息功能开发中')
  } else if (command === 'settings') {
    // 处理账号设置
    ElMessage.info('账号设置功能开发中')
  }
}

// 退出登录
const logout = () => {
  ElMessageBox.confirm('确定要退出登录吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    localStorage.removeItem('token')
    ElMessage({
      type: 'success',
      message: '已成功退出登录'
    })
    router.push('/login')
  }).catch(() => {})
}

// 初始化时获取数据
onMounted(() => {
  fetchCategories() // 加载服务类别数据
})
</script>

<style scoped>
/* 覆盖Element Plus的默认内边距 */
:deep(.el-header), :deep(.el-aside), :deep(.el-main) {
  padding: 0;
  margin: 0;
}

:deep(.el-main) {
  --el-main-padding: 20px;
  padding: var(--el-main-padding);
}

.home-container {
  width: 100vw;
  height: 100vh;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  background-color: #f5f7fa;
  position: absolute;
  left: 0;
  top: 0;
}

/* 头部样式 */
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  height: 60px;
  background-color: #fff;
  box-shadow: 0 1px 4px rgba(0,0,0,0.08);
  z-index: 1000;
  width: 100%;
  box-sizing: border-box;
}

.header-left {
  display: flex;
  align-items: center;
}

.logo {
  display: flex;
  align-items: center;
  margin-right: 20px;
  font-weight: bold;
  font-size: 18px;
}

.logo img {
  height: 32px;
  margin-right: 8px;
}

.nav-text {
  margin-left: 15px;
}

.header-left .el-icon {
  margin-right: 15px;
  font-size: 18px;
  cursor: pointer;
}

.header-right {
  display: flex;
  align-items: center;
}

.header-right .el-icon {
  font-size: 20px;
  margin: 0 15px;
  cursor: pointer;
}

.client-btn {
  display: flex;
  align-items: center;
  margin-right: 15px;
}

.user-info {
  display: flex;
  align-items: center;
  margin-left: 20px;
  cursor: pointer;
}

.user-info span {
  margin: 0 8px;
}

/* 主容器样式 */
.main-container {
  display: flex;
  flex: 1;
  overflow: hidden;
  width: 100%;
  margin: 0;
  padding: 0;
}

/* 侧边栏样式 */
.sidebar {
  background-color: #fff;
  height: 100%;
  box-shadow: 1px 0 4px rgba(0,0,0,0.08);
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-top: 20px;
  z-index: 900;
  width: 64px !important;
  min-width: 64px;
  flex-shrink: 0;
  margin: 0;
  padding-left: 0;
}

.menu-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 64px;
  cursor: pointer;
  color: #606266;
  transition: all 0.3s;
}

.menu-item span {
  font-size: 12px;
  margin-top: 5px;
}

.menu-item .el-icon {
  font-size: 20px;
}

.menu-item.active {
  color: #1989fa;
  background-color: #f0f7ff;
}

.menu-item:hover {
  background-color: #f5f7fa;
}

/* 主内容区域样式 */
.main-content {
  flex: 1;
  overflow-y: auto;
  width: calc(100% - 64px);
  box-sizing: border-box;
}

/* 应用推荐区域 - 改为网格布局适应宽度 */
.recommended-apps {
  margin-bottom: 30px;
  width: 100%;
}

.recommended-apps h2 {
  font-size: 18px;
  margin-bottom: 20px;
  font-weight: bold;
}

.app-cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  gap: 20px;
  width: 100%;
}

.app-card {
  width: 100%;
  cursor: pointer;
  transition: all 0.3s;
}

.app-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 15px 30px rgba(0,0,0,0.1);
}

.app-image {
  height: 160px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
}

.app-image img {
  max-width: 80%;
  max-height: 80%;
}

.app-title {
  margin: 12px 0 8px;
  font-size: 16px;
  font-weight: bold;
}

.app-description {
  font-size: 12px;
  color: #606266;
  margin-bottom: 15px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.app-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.app-author {
  display: flex;
  align-items: center;
}

.app-author span {
  margin-left: 8px;
  font-size: 12px;
}

.app-stats {
  font-size: 12px;
  color: #909399;
  display: flex;
  align-items: center;
}

.app-stats .el-icon {
  margin: 0 4px 0 8px;
}

/* 数据统计区域 - 改为网格布局 */
.statistics {
  margin-bottom: 30px;
  width: 100%;
}

.statistics h2 {
  font-size: 18px;
  margin-bottom: 20px;
  font-weight: bold;
}

.stat-cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 20px;
  width: 100%;
}

.stat-card {
  height: 100px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: #f9f9f9;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #1989fa;
  margin-bottom: 10px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

/* 服务人员列表样式 */
.staff-search {
  margin-bottom: 20px;
}

.staff-list {
  margin-top: 20px;
}

.staff-card {
  margin-bottom: 20px;
  transition: all 0.3s;
}

.staff-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0,0,0,0.1);
}

.staff-avatar {
  display: flex;
  justify-content: center;
  margin-bottom: 15px;
}

.staff-info {
  text-align: center;
  margin-bottom: 15px;
}

.staff-info h4 {
  font-size: 18px;
  margin: 0 0 5px 0;
}

.staff-title {
  color: #606266;
  font-size: 14px;
  margin: 0 0 10px 0;
}

.staff-rating {
  margin-bottom: 10px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.staff-rating span {
  margin-left: 5px;
  color: #ff9900;
  font-size: 14px;
}

.staff-tags {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 5px;
  margin-bottom: 15px;
}

.staff-actions {
  display: flex;
  justify-content: space-around;
}
</style>
